package com.lznAdmin.security.config;

import cn.hutool.core.collection.CollUtil;
import com.lznAdmin.system.entity.SysPermission;
import com.lznAdmin.system.entity.SysUser;
import com.lznAdmin.system.service.SysPermissionService;
import com.lznAdmin.system.service.SysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @program: lzn-manage-parent
 * @description: CustomUserDetailsService
 * @author: lzn
 * @create: 2021-07-26 17:31
 **/
@Component("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
    Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    PasswordEncoder passwordEncoder;
    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysPermissionService sysPermissionService;


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        logger.info("请求认证的用户名: " + username);

        // 1.根据请求用户名向数据库中查询用户信息
        SysUser sysUser = sysUserService.findByUsername(username);
        logger.info("根据输入的用户名查询到：" + sysUser.toString());
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名或密码错误");
        }
        // return new AccountUser(sysUser.getId(), sysUser.getUsername(), sysUser.getPassword(), );
        // 2.查询用户拥有权限
        List<SysPermission> sysPermissions = sysPermissionService.findByUserId(sysUser.getId());
        // logger.info(sysPermissions.toString());
        // 如果有用户，但无权限
        if (CollUtil.isEmpty(sysPermissions)) {
            // logger.info("有用户，无权限");
            return sysUser;
        }
        // 左侧菜单 动态渲染
        sysUser.setPermissions(sysPermissions);

        // 3.封装用户信息： username用户名,password数据库中的密码,authorities资源权限标识符
        List<GrantedAuthority> authorities = getUserAuthority(sysUser.getId());
        logger.info("authorities={}", authorities);
        // List<GrantedAuthority> authorities = new ArrayList<>();
        // for (SysPermission sp : sysPermissions) {
        //     // 权限标识
        //     authorities.add(new SimpleGrantedAuthority(sp.getCode()));
        //     logger.info("authorities={}",authorities);
        // }
        sysUser.setAuthorities(authorities);
        logger.info("sysUser={}", sysUser);
        //4. 交给 SpringSecurity 底层会校验是否身份合法。
        return sysUser;
    }

    /**
     * 获取用户权限信息（角色、菜单权限）
     *
     * @param userId
     * @return
     */
    public List<GrantedAuthority> getUserAuthority(Long userId) {
        // logger.info("getUserAuthority");
        // 角色(ROLE_admin)、菜单操作权限 sys:user:list
        String authority = sysUserService.getUserAuthorityInfo(userId);  // ROLE_admin,ROLE_normal,sys:user:list,....
        logger.info("authority111={}", authority);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(authority);
    }
}
